package com.wrl.mmall.controller.common.interceptor;

import com.wrl.mmall.common.Const;
import com.wrl.mmall.common.ServerResponse;
import com.wrl.mmall.pojo.User;
import com.wrl.mmall.util.CookieUtil;
import com.wrl.mmall.util.JsonUtil;
import com.wrl.mmall.util.RedisShardedPoolUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

/**
 * 自定义权限拦截器
 *
 * @author Wang Renlei
 * @Date 2019/10/18 0018
 */
@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {

    //进入controller之前的方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws Exception {
//        log.info("preHandle");
        //请求中的方法名
        HandlerMethod handlerMethod = (HandlerMethod) handle;
        //解析HandlerMethod
        //获取类名
        String methodName = handlerMethod.getMethod().getName();
        //获取方法名
        String className = handlerMethod.getBean().getClass().getSimpleName();

        if (StringUtils.equals(className, "UserManageController") && StringUtils.equals(methodName, "login")) {
            //如果拦截到的是登陆请求，就不进行拦截
            log.info("权限拦截器拦截到登陆请求 className{},methodName{}", className, methodName);
            return true;
        }

        //解析参数，具体的key和value，打印日志
        StringBuffer stringBuffer = new StringBuffer();
        Map<String, String[]> paramMap = request.getParameterMap();
        Iterator it = paramMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String mapKey = (String) entry.getKey();
            String mapValue = StringUtils.EMPTY;
            //request这个参数map，里面的value返回的是一个string数组
            Object value = entry.getValue();
            if (value instanceof String[]) {
                String[] strs = (String[]) value;
                mapValue = Arrays.toString(strs);
            }
            stringBuffer.append(mapKey).append("=").append(mapValue);
        }

        log.info("权限拦截器拦截到登陆请求 className{},methodName{},param{}", className, methodName, stringBuffer.toString());

        User user = null;
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isNotEmpty(loginToken)) {
            String userJsonStr = RedisShardedPoolUtil.get(loginToken);
            user = JsonUtil.stringToObj(userJsonStr, User.class);
        }
        if (user == null || (user.getRole().intValue() != Const.Role.ROLE_ADMIN)) {
            //返回false，不会去调用controller里面的方法

            //这里要reset，重置一下，否则会报异常
            response.reset();
            //重置只有要设置编码
            response.setCharacterEncoding("UTF-8");
            //设置返回值的类型，全部是json
            response.setContentType("application/json;charset=UTF-8");

            //创建写到前台页面上的对象
            PrintWriter writer = response.getWriter();

            if (user == null) {
                //针对富文本上传图片，使用特定的是接口返回格式
                if (StringUtils.equals(className, "ProductManageController") && StringUtils.equals(methodName, "")) {
                    Map<String, Object> resultMap = Maps.newHashMap();
                    resultMap.put("success", false);
                    resultMap.put("msg", "请登录管理员");
                    writer.print(JsonUtil.objToString(resultMap));
                }else{
                    writer.print(JsonUtil.objToString(ServerResponse.createByErrorMessage("拦截器拦截，用户未登陆")));
                }
            } else {
                if (StringUtils.equals(className, "ProductManageController") && StringUtils.equals(methodName, "richtextImgUpload")) {
                    Map<String, Object> resultMap = Maps.newHashMap();
                    resultMap.put("success", false);
                    resultMap.put("msg", "无权限操作");
                    writer.print(JsonUtil.objToString(resultMap));
                }else{
                    writer.print(JsonUtil.objToString(ServerResponse.createByErrorMessage("拦截器拦截，用户未无权限操作")));
                }
            }
            //先清空
            writer.flush();
            //再关闭
            writer.close();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
//        log.info("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
//        log.info("afterCompletion");
    }
}
